package ldh.im.fxbase.emoji;

import javafx.scene.image.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;


/**
 * Created by UltimateZero on 9/11/2016.
 */
public class ImageCache {

	private static final Logger LOGGER = LoggerFactory.getLogger(ImageCache.class);

	private ConcurrentHashMap<String, WeakReference<Image>> map;
	private static final ImageCache INSTANCE = new ImageCache();
	public static ImageCache getInstance() {
		return INSTANCE;
	}
	private ImageCache() {
		map = new ConcurrentHashMap<>();
	}

	public synchronized Image getImage(String path) {
		try {
			WeakReference<Image> ref = map.get(path);
			if(ref == null || ref.get() == null) {
				ref = new WeakReference<Image>(new Image(path, true));
				map.put(path, ref);
			}
			return ref.get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getImagePath(String hexString) {
		try {
			Emoji emoji = EmojiOne.getInstance().getEmoji(String.format(":%s:", hexString));
			if (emoji != null) {
				return getEmojiImagePath(emoji.getHex());
			}
			String result =  getEmojiImagePath(hexString);
			return result;
		} catch (Exception e) {
			LOGGER.error("emoji error {}", hexString);
			return getEmojiImagePath("274c");
		}
	}

	private String getEmojiImagePath(String hexStr) {
		URL url = getClass().getResource("/ldh/im/fxbase/emojione/png_40/" + hexStr + ".png");
		if (url == null) {
			LOGGER.error("emojo error, {}", hexStr);
			return null;
		}
		return url.toExternalForm();
	}
}
